package com.zzmcc.wechat.util;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.smart4j.framework.FrameworkConstant;
import org.smart4j.framework.util.CastUtil;
import org.smart4j.framework.util.JsonUtil;
import org.smart4j.framework.util.WebUtil;

import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;


public class MyWebUtil extends WebUtil {

    private static final Logger logger = LoggerFactory.getLogger(MyWebUtil.class);

    public static void writeXml(HttpServletResponse response, Object data) {
        try {
            // 设置响应头
            response.setContentType("application/xml"); // 指定内容类型
            response.setCharacterEncoding("utf-8"); // 防止中文乱码
            // 向响应中写入数据
            PrintWriter printWriter = response.getWriter();
            printWriter.write(CastUtil.castString(data));
            printWriter.flush();
            printWriter.close();
        } catch (Exception e) {
            logger.error("在响应中写数据出错！", e);
            throw new RuntimeException(e);
        }
    }

    /**
     * 将数据以 HTML 格式写入响应中（在 JS 中获取的是 JSON 字符串，而不是 JSON 对象）
     */
    public static void writeHTML(HttpServletResponse response, Object data) {
        try {
            // 设置响应头
            response.setContentType("text/html"); // 指定内容类型为 HTML 格式
            response.setCharacterEncoding(FrameworkConstant.UTF_8); // 防止中文乱码
            // 向响应中写入数据
            PrintWriter writer = response.getWriter();
            writer.write(CastUtil.castString(data));
            writer.flush();
            writer.close();
        } catch (Exception e) {
            logger.error("在响应中写数据出错！", e);
            throw new RuntimeException(e);
        }
    }


}
